import json

from django.http import JsonResponse
from django.shortcuts import render
from django.views import View

from bmodels.models import BookInfo


class BookView(View):

    def post(self, request):
        # 1.save()
        # book = BookInfo()
        # book.btitle = '司藤'
        # book.bpub_date = '2020-02-02'
        # # save() 触发 orm和mysql教互
        # book.save()

        # 2.create()
        # book = BookInfo.objects.create(
        #     btitle='司命',
        #     bpub_date='2008-07-02'
        # )

        # 1.解析 参数
        json_dict = json.loads(request.body)

        book = BookInfo.objects.create(
            btitle=json_dict.get('name'),
            bpub_date=json_dict.get('date'),
        )


        data = {'msg': f"{book}-添加成功!"}
        return JsonResponse(data)

    def get(self, request):
        # 查询一个
        book = BookInfo.objects.get(id=2)

        # 查询所有
        books = BookInfo.objects.all()

        data_list = []
        for book in books:
            data_list.append({'name': book.btitle})

        return JsonResponse(data_list, safe=False)

    def put(self, request):
        # 1. save()
        # book = BookInfo.objects.get(id=6)
        # book.btitle = 'sitianming'
        # book.save()

        # 2.update()
        BookInfo.objects.filter(id=5).update(btitle='景甜')

        data = {'msg': "改完了!"}
        return JsonResponse(data)

    def delete(self, request):
        # 1. delete()
        # book = BookInfo.objects.get(id=6)
        # book.delete()

        # 2.delete()
        book = BookInfo.objects.filter(id=5).delete()

        data = {'msg': f'{book}-删除成功'}
        return JsonResponse(data)
"""
    #C
        save()          模型类名.objects.create(属性=值)
    #R
        get(属性=值) all() filter(属性=值)
    #U
        save()          模型类名.objects.filter(属性=查询条件值).update(属性=修改值)
    #D
        book.delete()   模型类名.objects.filter(属性=查询条件值).delete()
"""
# book = BookInfo.objects.get(id=1).delete()
# BookInfo.objects.filter(id=1).delete()



"""
    取反函数: exclude()
    
    相等 exact
    包含: contains startswith endswith
    判空: isnull
    判范围: in
    比较运算: lt gt lte gte
    日期: year month 
    
"""

"""
    关联查询:
    1:n
        默认 1.n_set.all()
        
        只能有一个存在!
        修改 n 多模型--字段(related_name = 'xxx')
        1.xx.all()
    
    n:1
        n.外键属性  === > 数据对象
        n.外键属性_id  === > 数字
"""